package com.cloudfast.channel;

import java.io.IOException;
import java.net.SocketException;

import com.cloudfast.config.property.c.DefaultProperty;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jcraft.jsch.JSchException;

/**
 * ftp 连接类
 *
 * @author liuyw
 */
public class FTPChannel {

    private static final Logger logger = LoggerFactory.getLogger(Logger.class);

    /**
     * sftp获取连接通道
     *
     * @param storageConfig 会话创建信息
     * @param timeout       会话超时时间
     * @return 文件通道
     * @throws JSchException 构件内部异常
     */
    public FTPClient getChannel(DefaultProperty storageConfig, int timeout) {
        String ftpHost = storageConfig.getHost();
        int ftpPort = Integer.parseInt(storageConfig.getPort());
        String ftpUserName = storageConfig.getUsername();
        String ftpPassword = storageConfig.getPassword();
        // 创建ftpclient对象
        FTPClient ftp = null;
        try {
            ftp = new FTPClient();
            // 连接FPT服务器,设置IP及端口
            ftp.connect(ftpHost, ftpPort);
            // 设置用户名和密码
            ftp.login(ftpUserName, ftpPassword);
            // 设置连接超时时间,5000毫秒
            ftp.setConnectTimeout(60000);
            // 设置中文编码集，防止中文乱码
            ftp.setControlEncoding("UTF-8");
            if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                ftp.disconnect();
                throw new RuntimeException("未连接到FTP，用户名或密码错误");
            }

        } catch (SocketException e) {
            throw new RuntimeException("连接FTP失败,请确认配置");
        } catch (IOException e) {
            throw new RuntimeException("连接FTP失败,请确认配置");
        }
        return ftp;
    }

    /**
     * 关闭FTP方法
     *
     * @param ftp
     * @return
     */
    public boolean closeFTP(FTPClient ftp) {

        try {
            ftp.logout();
        } catch (Exception e) {
            logger.error("FTP关闭失败");
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                    logger.error("FTP关闭失败");
                }
            }
        }

        return false;

    }

}
